package cn.rengy.tpa.wxmp.token.ticket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.token.AccessToken;

public class TicketApi {
	private static Logger logger = LoggerFactory.getLogger(TicketApi.class);
	private static final String TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=";
	
	public static TicketResponse ticket(TicketType ticketType,AccessToken accessToken) throws WeChatException{
		StringBuilder sb=new StringBuilder(TICKET_URL);
		sb.append(ticketType.name()).append("&access_token=");
		String url0=sb.toString();
		String url;
		TicketResponse ticketResponse=null;
		for(int i=0;i<3;i++){
			url=url0.concat(accessToken.token());
			String httpResult = HttpUtils.get(url);
			logger.debug("ticketResult:{}",httpResult);
			//System.out.println(httpResult);
			ticketResponse=new TicketResponse(httpResult);
			int errcode=ticketResponse.getErrcode();
			if(errcode==0){
				break;
			}else if(errcode==40001){//token不可用
				accessToken.refresh();
			}
		}
		if(ticketResponse==null||!ticketResponse.isSuccess()){
			throw new WeChatException(ticketResponse.getErrcode(),ticketResponse.getErrmsg());
		}
		return ticketResponse;
	}
}
